import React from 'react';

/**
 * 组件卸载阶段，要执行的钩子函数
 *
 * componentWillUnmount
 */
export class App extends React.Component {
  constructor() {
    console.log('1. constructor()');
    super();
    // 设置组件状态
    this.state = {
      visible: true,
    };
  }

  handleClick = () => {
    // 修改组件状态
    this.setState({
      visible: !this.state.visible,
    });
  };

  render() {
    console.log('2. render');
    return (
      <div>
        <h1 id="title">父组件</h1>
        <button onClick={this.handleClick}>消失/回来</button>
        <hr />
        {this.state.visible ? <Counter /> : <></>}
      </div>
    );
  }

  componentDidMount() {
    console.log('3. componentDidMount()');
  }

  componentDidUpdate() {
    console.log('4. componentDidUpdate()');
  }
}

class Counter extends React.Component {
  constructor() {
    console.log('子组件 1. constructor()');
    super();
    // 组件卸载阶段清除计时器
    this.timerId = setInterval(() => {
      console.log('子组件计时器执行');
    }, 500);
  }

  render() {
    console.log('子组件 2. render');
    return (
      <div>
        <h3>子组件</h3>
      </div>
    );
  }

  componentDidMount() {
    console.log('子组件 3. componentDidMount()');
  }

  componentDidUpdate() {
    console.log('子组件 4. componentDidUpdate()');
  }

  componentWillUnmount() {
    // 组件卸载阶段清除计时器
    clearInterval(this.timerId);
    console.log('子组件 5. componentWillUnmount()');
  }
}

export default App;
